import axios from 'axios'
import store from '@/store';
axios.defaults.withCredentials = true;
import config from '@/common/config'
/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
// 创建 axios 实例
const service = axios.create({
	baseURL: config.baseUrl, // api base_url
	timeout: 9000, // 请求超时时间
	async: true,
	crossDomain: true,	
	withCredentials: true
})
let ACCESS_TOKEN = ''
// #ifdef H5
ACCESS_TOKEN = window.sessionStorage.getItem('ACCESS_TOKEN');
// #endif
// #ifndef H5
ACCESS_TOKEN = uni.getStorageSync('ACCESS_TOKEN');
// #endif

const err = (error) => {
	if (error.response) {
		let that = this;
		let data = error.response.data
		const token = ACCESS_TOKEN
		console.log("------异常响应------", token)
		console.log("------异常响应------", error.response.status)
		switch (error.response.status) {
			case 403:
				uni.showToast({
					title: '拒绝访问',
					duration: 2000
				});
				break
			case 500:
				console.log("------error.response------", error.response)
				// update-begin- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
				let type = error.response.request.responseType;
				if (type === 'blob') {
					blobToJson(data);
					break;
				}
				// update-end- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
				if (token && data.message.includes("Token失效")) {
					// update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
					store.dispatch('Logout').then(() => {
						try {
							let path = window.document.location.pathname
							console.log("location pathname -> " + path)
							if (path.indexOf('/login/login/login') == -1) {
								uni.navigateTo({
									url: '/pages/common-service/profile/login/login/login?path=' +
										path
								})
							}
						} catch (e) {
							window.location.reload()
						}
					})
					// update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
				} else if (data.exception.includes("org.apache.shiro.authc.AuthenticationException")) {
					store.dispatch('Logout').then(() => {
						try {
							let path = window.document.location.pathname
							console.log("location pathname -> " + path)
							if (path.indexOf('/login/login/login') == -1) {
								uni.navigateTo({
									url: '/pages/common-service/profile/login/login/login?path=' +
										path
								})
							}
						} catch (e) {
							window.location.reload()
						}
					})

				}
				break
			case 404:
				uni.showToast({
					title: '很抱歉，资源未找到!',
					duration: 2000
				});
				break
			case 504:
				uni.showToast({
					title: '网络超时',
					duration: 2000
				});
				break
			case 401:
				uni.showToast({
					title: '未授权，请重新登录',
					duration: 2000
				});
				if (token) {
					store.dispatch('Logout').then(() => {
						setTimeout(() => {
							window.location.reload()
						}, 1500)
					})
				}
				break
			default:
				uni.showToast({
					title: data.message,
					duration: 2000
				});
				break
		}
	}
	return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
	const token = ACCESS_TOKEN
	if (token) {
		config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
	}
	//update-end-author:taoyan date:2020707 for:多租户
	if (config.method == 'get') {
		if (config.url.indexOf("sys/dict/getDictItems") < 0) {
			config.params = {
				_t: Date.parse(new Date()) / 1000,
				...config.params
			}
		}
	}
	return config
}, (error) => {
	return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
		return response.data
	}, err),
	/**
	 * Blob解析
	 * @param data
	 */
	function blobToJson(data) {
		let fileReader = new FileReader();
		let token = ACCESS_TOKEN
		fileReader.onload = function() {
			try {
				let jsonData = JSON.parse(this.result); // 说明是普通对象数据，后台转换失败
				console.log("jsonData", jsonData)
				if (jsonData.status === 500) {
					console.log("token----------》", token)
					if (token && jsonData.message.includes("Token失效")) {
						uni.showModal({
							title: '登录已过期',
							content: '很抱歉，登录已过期，请重新登录',
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定重新登录');
									store.dispatch('Logout').then(() => {
										window.location.reload()
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				}
			} catch (err) {
				// 解析成对象失败，说明是正常的文件流
				console.log("blob解析fileReader返回err", err)
			}
		};
		fileReader.readAsText(data)
	}
export default service
